package com.css.prompt.controller;

import java.util.List;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.css.prompt.dto.MyPromptDto;
import com.css.prompt.model.MyPrompt;
import com.css.prompt.service.MyPromptService;

@RestController
@RequestMapping("/api/public-prompts")
public class MyPromptVersionedApiController {

    private final MyPromptService service;

    public MyPromptVersionedApiController(MyPromptService service) {
        this.service = service;
    }

    /**
     * 拉取提示词（默认最新）
     * 示例：
     *  - GET /api/public-prompts/博客文章优化器
     *  - GET /api/public-prompts/博客文章优化器?version=1.0.0
     */
    @GetMapping("{title}")
    public ResponseEntity<MyPrompt> getPromptByTitleAndVersion(
            @PathVariable String title,
            @RequestParam(value = "version", required = false) String version) {

        return version != null
                ? service.getByTitleAndVersion(title, version)
                    .map(ResponseEntity::ok)
                    .orElse(ResponseEntity.notFound().build())
                : service.getLatestByTitle(title)
                    .map(ResponseEntity::ok)
                    .orElse(ResponseEntity.notFound().build());
    }

    /**
     * 获取该提示词的所有历史版本
     */
    @GetMapping("{title}/versions")
    public List<MyPrompt> getAllVersions(@PathVariable String title) {
        return service.getAllVersions(title);
    }
    
    @GetMapping("latest")
    public ResponseEntity<MyPromptDto> getLatestPrompt(@RequestParam String title) {
    	return service.getLatestVersion(title)
                .map(MyPromptDto::from)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("version")
    public ResponseEntity<MyPromptDto> getSpecificVersion(@RequestParam String title,@RequestParam String version) {
        return service.getSpecificVersion(title, version).map(MyPromptDto::from).map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
    }
}

